package com.bryant.miantong.utils
import com.tencent.mmkv.MMKV

object MMKVManager {
    private const val KEY_USER_TOKEN = "user_token"
    private const val KEY_USER_ID = "user_id"
    private const val KEY_USER_NAME = "user_name"
    private const val KEY_IS_LOGGED_IN = "is_logged_in"

    private val mmkv by lazy { MMKV.defaultMMKV() }

    /**
     * 初始化MMKV
     */
    fun initializeMMKV(): Boolean {
        return try {
            // MMKV.initialize() 应该在Application中调用
            true
        } catch (e: Exception) {
            false
        }
    }

    /**
     * 保存用户登录信息
     */
    fun saveLoginInfo(token: String, userId: String? = null, userName: String? = null) {
        mmkv.encode(KEY_USER_TOKEN, token)
        userId?.let { mmkv.encode(KEY_USER_ID, it) }
        userName?.let { mmkv.encode(KEY_USER_NAME, it) }
        mmkv.encode(KEY_IS_LOGGED_IN, true)
    }

    /**
     * 获取用户token
     */
    fun getUserToken(): String? {
        return mmkv.decodeString(KEY_USER_TOKEN)
    }

    /**
     * 获取用户ID
     */
    fun getUserId(): String? {
        return mmkv.decodeString(KEY_USER_ID)
    }

    /**
     * 获取用户名
     */
    fun getUserName(): String? {
        return mmkv.decodeString(KEY_USER_NAME)
    }

    /**
     * 检查用户是否已登录
     */
    fun isLoggedIn(): Boolean {
        return mmkv.decodeBool(KEY_IS_LOGGED_IN, false) && !getUserToken().isNullOrEmpty()
    }

    /**
     * 清除登录信息
     */
    fun clearLoginInfo() {
        mmkv.encode(KEY_USER_TOKEN, "")
        mmkv.encode(KEY_USER_ID, "")
        mmkv.encode(KEY_USER_NAME, "")
        mmkv.encode(KEY_IS_LOGGED_IN, false)
    }

    /**
     * 获取所有用户信息
     */
    fun getAllUserInfo(): Map<String, Any?> {
        return mapOf(
            "token" to getUserToken(),
            "userId" to getUserId(),
            "userName" to getUserName(),
            "isLoggedIn" to isLoggedIn()
        )
    }
}
